﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EntityDesigner2.Controls
{
    public class EdListBox : ListBox
    {
        public bool IsUpdating { get; set; }
        public bool IsWorking { get; set; }
        public int RowIndex { get; set; }
        public int ColumnIndex { get; set; }

        public EdDataGridView DataGridView { get; }

        public DataGridViewTextBoxEditingControl EditingControl { get; set; }

        public EdListBox(DataGridView view)
        {
            this.IsWorking = false;
            this.IsUpdating = false;
            this.ColumnIndex = 0;
            this.RowIndex = 0;
            this.DataGridView = (EdDataGridView)view;
        }

        /// <summary>
        /// 更新值到列表
        /// </summary>
        public void UpdateValueToDataGridView()
        {
            if (this.SelectedIndex < 0) return;
            this.IsUpdating = true;
            string value = (string)this.Items[this.SelectedIndex];
            this.DataGridView.Rows[this.RowIndex].Cells[this.ColumnIndex].Value = value;
            if (this.EditingControl != null)
            {
                this.EditingControl.Text = value;
                this.EditingControl.SelectionStart = 0;
                this.EditingControl.SelectionLength = value.Length;
            }
            this.Visible = false;
            this.IsUpdating = false;
            this.DataGridView.IsExternalControl = false;
        }

        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            base.OnSelectedIndexChanged(e);
            if (!this.Focused) return;
            UpdateValueToDataGridView();
        }

        protected override void OnLostFocus(EventArgs e)
        {
            base.OnLostFocus(e);
            this.Visible = false;
            this.DataGridView.IsExternalControl = true;
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
            if (!this.Visible) return;
            this.Width = this.DataGridView.Columns[this.ColumnIndex].Width;
        }
    }
}
